package com.play.ballen

import android.annotation.SuppressLint
import android.app.Activity
import android.app.Application
import android.content.Context
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.util.Log
import com.mw.plp.uim.DemoApplication
import com.play.ballen.config.BallenConfig
import com.play.ballen.network.RetrofitManager
import com.play.ballen.service.OKHttpUpdateHttpService
import com.play.ballen.utils.UserInfoManager
import com.play.ballen.view.BallenTitleBarFactory
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.xuexiang.xupdate.XUpdate
import com.yariksoffice.lingver.Lingver
import com.yuven.appframework.base.AppFrameWorkApplication
import com.yuven.appframework.config.AppFrameWorkConstant
import com.yuven.appframework.network.NetConfiguration
import com.yuven.appframework.util.FileUtil
import com.yuven.appframework.widget.titlebar.TitleBarConfig
import com.yuven.baselib.utils.Logger
import java.io.File
import java.util.Collections
import java.util.LinkedList


class BallenApplication : AppFrameWorkApplication() {


    init {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator { context, layout ->
            layout.setPrimaryColorsId(android.R.color.transparent) //全局设置主题颜色
            ClassicsHeader(context)
        }
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator { context, layout -> //指定为经典Footer，默认是 BallPulseFooter
            ClassicsFooter(context).setDrawableSize(20f)
        }
    }

    private val mActivitys = Collections
        .synchronizedList(LinkedList<Activity>())
    override fun attachBaseContext(base: Context?) {
        super.attachBaseContext(base)
    }

    override fun onCreate() {
        super.onCreate()
        initConfig()
        UserInfoManager.readUserInfoFromMMKV()
        DemoApplication.getInstance().withInit(this)
        registerActivityListener();
    }




    companion object {
        private var sMainThreadHandler: Handler? = null
        private var sInstance: BallenApplication? = null
        fun getInstance():BallenApplication? {
            if (sInstance == null) {
                try {
                    val clazz = Class.forName("android.app.ActivityThread")
                    val method = clazz.getMethod("currentApplication", *arrayOf())
                    val obj = method.invoke(null, *arrayOf())
                    if (obj != null && obj is BallenApplication) {
                        sInstance = obj
                    }
                } catch (e: java.lang.Exception) {
                    e.printStackTrace()
                }
            }
            return sInstance
        }


        @JvmStatic
        fun postDelayed(runnable: Runnable?, delayMillis: Long) {
            if (sMainThreadHandler == null) {
                getMainThreadHandler()
            }
            if (runnable != null) {
                sMainThreadHandler?.postDelayed(runnable, delayMillis)
            }
        }

        @SuppressLint("SoonBlockedPrivateApi")
        private fun getMainThreadHandler() {
            try {
                val clazz = Class.forName("android.app.ActivityThread")
                val field = clazz.getDeclaredField("sMainThreadHandler")
                field.isAccessible = true
                val obj = field[clazz]
                if (obj != null && obj is Handler) {
                    sMainThreadHandler = obj
                }
            } catch (e: java.lang.Exception) {
                e.printStackTrace()
            }
        }
    }

    private fun initConfig() {
        Lingver.init(this, BallenConfig.DEFAULT_LANGUAGE)
        Logger.initLogger(
            Logger.VERBOSE,
            true,
            FileUtil.LOG_DIR + File.separator + BallenConfig.FILE_LOG_NAME
        )
        RetrofitManager.getInstance().init(NetConfiguration.instance)
        AppFrameWorkConstant.PIC_SAVE_DIR_NAME = BallenConfig.PIC_SAVE_DIR_NAME
        AppFrameWorkConstant.FILE_PROVIDER_AUTHORITY = BallenConfig.FILE_PROVIDER_AUTHORITY
        TitleBarConfig.setTitleBarFactory(BallenTitleBarFactory())

        //初始化更新框架
        //初始化更新框架
        XUpdate.get()
            .isWifiOnly(false) //默认设置只在wifi下检查版本更新
            .isGet(true) //默认设置使用get请求检查版本
            .isAutoMode(false) //默认设置非自动模式，可根据具体使用配置
            .setIUpdateHttpService(OKHttpUpdateHttpService()) //这个必须设置！实现网络请求功能。
            .init(this) //这个必须初始化

    }

    fun pushActivity(activity: Activity) {
        mActivitys.add(activity)
        Log.d("xyp","activityList:size:${mActivitys.size}")
    }

    fun popActivity(activity: Activity) {
        mActivitys.remove(activity)
        Log.d("xyp","activityList:size:${mActivitys.size}")
    }

    fun currentActivity(): Activity? {
        return if (mActivitys.isNullOrEmpty()) {
            null
        } else {
            mActivitys[mActivitys.size - 1]
        }
    }

    fun finishCurrentActivity() {
        currentActivity()?.let { finishActivity(it) }
    }

    fun finishActivity(activity: Activity) {
        mActivitys.remove(activity)
        activity.finish()
    }

    fun finishActivity(cls: Class<*>) {
        for (activity in mActivitys) {
            if (activity.javaClass == cls) {
                finishActivity(activity)
            }
        }
    }

    fun findActivity(cls: Class<*>): Activity? {
        for (activity in mActivitys) {
            if (activity.javaClass == cls) {
                return activity
            }
        }
        return null
    }

    fun getTopActivity(): Activity? {
        return synchronized(mActivitys) {
            val size = mActivitys.size - 1
            if (size < 0) {
                null
            } else {
                mActivitys[size]
            }
        }
    }

    fun getTopActivityName(): String? {
        return synchronized(mActivitys) {
            val size = mActivitys.size - 1
            if (size < 0) {
                null
            } else {
                mActivitys[size].javaClass.name
            }
        }
    }

    fun finishAllActivity() {
        for (activity in mActivitys) {
            activity.finish()
        }
        mActivitys.clear()
    }

    fun appExit() {
        try {
            finishAllActivity()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun registerActivityListener() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks {
                override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
                    // 监听到 Activity 创建事件 将该 Activity 加入 list
                    pushActivity(activity)
                }

                override fun onActivityStarted(activity: Activity) {}

                override fun onActivityResumed(activity: Activity) {}

                override fun onActivityPaused(activity: Activity) {}

                override fun onActivityStopped(activity: Activity) {}

                override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}

                override fun onActivityDestroyed(activity: Activity) {
                    if (mActivitys.isNullOrEmpty()) {
                        return
                    }
                    if (mActivitys.contains(activity)) {
                        // 监听到 Activity 销毁事件 将该 Activity 从 list 中移除
                        popActivity(activity)
                    }
                }
            })
        }
    }


}